package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @Author: dw
 * @Date 2022/3/16 23:56
 */
@RestController
@RequestMapping("/shoppingCart")
public class ShoppingCartController {

    @Autowired(required = false)
    private ShoppingCartService shoppingCartService;

    @Autowired(required = false)
    private HttpSession session;

    /**
     * 查询购物车所有数据
     * @return
     */
    @RequestMapping("/list")
    public R<List<ShoppingCart>> findAll(){
        List<ShoppingCart> shoppingCartList = shoppingCartService.findAll();
        return R.success(shoppingCartList);
    }

    /**
     * 添加菜品到购物车
     * @param shoppingCart
     * @return
     */
    @RequestMapping("/add")
    public R<ShoppingCart> addCart(@RequestBody ShoppingCart shoppingCart){
        //接收数据封装到shoppingCart对象中
        Long id = (Long) session.getAttribute("user");
        //将用户的id保存到shoppingCart中(因为前端没传递userId，所以我们获取登录用户的id)
        shoppingCart.setUserId(id);
        ShoppingCart shoppingCartNew = shoppingCartService.save(shoppingCart);
        return R.success(shoppingCartNew);
    }

    /**
     * 根据UserId清空购物车数据
     * @return
     */
    @DeleteMapping("/clean")
    public R<String> deleteByUserId(){
        shoppingCartService.deleteByUserId();
        return R.success("清空购物车成功");
    }

    /**
     * 减少菜品到购物车
     * @param shoppingCart
     * @return
     */
    @RequestMapping("/sub")
    public R<String> subCart(@RequestBody ShoppingCart shoppingCart){
        //接收数据封装到shoppingCart对象中
        Long id = (Long) session.getAttribute("user");
        //将用户的id保存到shoppingCart中(因为前端没传递userId，所以我们获取登录用户的id)
        shoppingCart.setUserId(id);

        shoppingCartService.reduce(shoppingCart);

        return R.success("删除成功");
    }
}
